import io
import logging

import cv2
import numpy as np
from PIL.Image import Image
from nicegui import ui, events


class OpencvDefectFrame:
    def __init__(self, log_handler: logging):
        self.logger = log_handler
        self._build()

    def mouse_handler(self, e: events.MouseEventArguments):
        color = 'SkyBlue' if e.type == 'mousedown' else 'SteelBlue'
        self.ii.content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="15" fill="none" stroke="{color}" stroke-width="4" />'
        ui.notify(f'{e.type} at ({e.image_x:.1f}, {e.image_y:.1f})')

    def handle_plpic_upload(self, e: events.UploadEventArguments):
        self.logger.debug('handle DAF upload')
        bytes_data = e.content.read()

        # 使用BytesIO将字节数据转为文件对象
        image_bytes = io.BytesIO(bytes_data)

        # 使用PIL的Image类从文件对象中读取图像
        pil_image = Image.open(image_bytes)

        # 如果需要转换为OpenCV的图像格式
        opencv_image = np.array(pil_image)
        # 如果是灰度图
        opencv_image = cv2.cvtColor(opencv_image, cv2.COLOR_RGB2GRAY)

        self.logger.debug(f'uploaded file length={len(image_bytes)}')

        # content.set_content(text)
        # dialog.open()

    def _build(self):
        with ui.row().classes('w-full items-end justify-items-end'):
            ui.label('产线缺陷检测').classes('text-h6 font-bold')
        with ui.row().classes('w-full items-end justify-items-end'):
            ui.upload(label='产线照片上传', on_upload=self.handle_plpic_upload).props(
                'accept=.json color=blue-11').classes('max-w-full')
            label_daf_upload = ui.label('').classes(
                'italic text-xs text-red-600 text-opacity-75')
        ui.separator()
        with ui.row().classes('w-full items-end justify-items-end'):
            with ui.column().classes('w-full h-full'):
                src = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'
                self.ii = ui.interactive_image(size=(800, 600), on_mouse=self.mouse_handler,
                                               events=['mousedown', 'mouseup'], cross=True)
